<?php
declare(strict_types=1);
/**
 * Created by PhpStorm
 * User: Administrator
 * Date: 2023/8/4
 * Time: 10:27:20
 */

namespace Service\CommodityService;

use App\Model\BbcModel\Goods;
use App\Model\BbcModel\GoodsClass;
use Service\Code\Normal;
use Service\BaseService;
use function PHPStan\dumpType;
use function Symfony\Component\Translation\t;

class GoodsClassService extends BaseService
{

    public function makeWhere($param){
        $where = [
            ['cid','=',$param['cid']],
            ['sid','=',$param['sid']],
            ['df','=',0]
        ];

        if(isset($param['name']) && $param['name'] != ''){
            $where[] = ['name','like','%{$param[name]}%'];
        }

        if(isset($param['start_time']) && $param['start_time'] != ''){
            $start_time = strtotime($param['start_time']);
            $where[] = ['md','>',$start_time];
        }

        if(isset($param['start_time']) && $param['end_time'] != ''){
            $end_time = strtotime($param['end_time']);
            $where[] = ['md','<',$end_time];
        }

        if(isset($param['status']) && $param['status'] != ''){
            $where[] = ['show','=',$param['status']];
        }
        return $where;
    }

    public function goodsClassList($param)
    {
        $where = $this->makeWhere($param);

        $data_list = GoodsClass::instance()
            ->where($where)
            ->orderByRaw('id desc')
            ->select(['id','name','pid','icon','md','show'])
            ->get()->toArray();
        foreach ($data_list as &$v){
            if($v['md']){
                $v['md'] = date('Y-m-d H:i:s',$v['md']);
            }
        }
        $list = tree($data_list,0,'id','pid');
        return Normal::returnCode(Normal::SUC,'请求成功',$list);
    }

    public function add($param){
        if(!isset($param['name']) || !$param['name']){
            return Normal::returnCode(Normal::FAIL,'缺少分类名称');
        }

        $res = GoodsClass::instance()
            ->insert([
                'sid'  => $param['sid'],
                'cid'  => $param['cid'],
                'pid'  => $param['pid'] ?? 0,
                'name' => $param['name'],
                'icon' => $param['icon'] ?? '',
                'sort' => $param['sort'] ?? 0,
                'cd'   => time(),
                'md'   => time(),
            ]);
        if(!$res){
            return Normal::returnCode(Normal::FAIL,'新增失败');
        }
        return Normal::returnCode(Normal::SUC,'新增成功');
    }

    public function edit($param){
        if(!isset($param['id']) || !$param['id']){
            return Normal::returnCode(Normal::FAIL,'缺少分类ID');
        }
        if(!isset($param['name']) || !$param['name']){
            return Normal::returnCode(Normal::FAIL,'缺少分类名称');
        }

        $info = GoodsClass::instance()
            ->where(['cid'=>$param['cid'],'df'=>0,'id'=>$param['id']])
            ->first();
        if(!$info){
            return Normal::returnCode(Normal::FAIL,'分类不存在');
        }

        $res = GoodsClass::instance()
            ->where(['id'=>$param['id']])
            ->update([
                'name' => $param['name'],
                'icon' => $param['icon'] ?? $info['icon'],
                'sort' => $param['sort'] ?? $info['sort'],
                'md' => time(),
            ]);

        if(!$res){
            return Normal::returnCode(Normal::FAIL,'编辑失败');
        }

        return Normal::returnCode(Normal::SUC,'编辑成功');
    }

    public function del($param){
        if(!isset($param['class_ids']) || !$param['class_ids']){
            return Normal::returnCode(Normal::FAIL,'缺少分类ID');
        }
        if(!is_array($param['class_ids'])){
            return Normal::returnCode(Normal::FAIL,'分类ID参数类型错误');
        }
        $has = GoodsClass::instance()
            ->where(['cid'=>$param['cid'],'df'=>0])
            ->whereIn('id',$param['class_ids'])
            ->exists();
        if(!$has){
            return Normal::returnCode(Normal::FAIL,'分类不存在');
        }

        $class_list = GoodsClass::instance()
            ->where(['cid'=>$param['cid'],'df'=>0])
            ->get()->toArray();

        $class_ids = [];
        foreach ($param['class_ids'] as $v){
            $class_ids[] = $this->getChildId($class_list,$v);
        }
        $class_arr = $this->flattenArray($class_ids);
        $has = Goods::instance()
            ->where(['cid'=>$param['cid'],'df'=>0])
            ->whereIn('class_id',$class_arr)
            ->exists();
        if($has){
            return Normal::returnCode(Normal::FAIL,'分类或子分类有商品不能删除');
        }

        $res = GoodsClass::instance()
            ->whereIn('id',$class_arr)
            ->update(['df'=>1,'md'=>time()]);
        if(!$res){
            return Normal::returnCode(Normal::FAIL,'删除失败');
        }

        return Normal::returnCode(Normal::SUC,'删除成功');

    }

    /**
     * 递归获取所有子元素包含本级元素
     * @param $array
     * @param $pid
     * @return array
     */
    public function getChildId($array, $id = 0)
    {
        $arr = array();
        foreach($array as $v){
            if($v['pid'] == $id){
                $arr[] = $v['id'];
                $arr = array_merge($arr,$this->getChildId($array,$v['id']));
            };
        };
        $arr[] = $id;
        return array_unique($arr);
    }

    /**
     * 二维数组转一位数组
     * @param $array
     * @return array
     */
    public function flattenArray($array){
        return call_user_func_array('array_merge',$array);
    }

    public function changeStatus($param){
        if(!isset($param['class_ids']) || !$param['class_ids']){
            return Normal::returnCode(Normal::FAIL,'缺少分类ID');
        }

        if(!isset($param['status']) || !in_array($param['status'],[0,1])){
            return Normal::returnCode(Normal::FAIL,'状态参数错误');
        }
        if(!is_array($param['class_ids'])){
            return Normal::returnCode(Normal::FAIL,'分类ID参数类型错误');
        }
        $class_list = GoodsClass::instance()
            ->where(['cid'=>$param['cid'],'df'=>0])
            ->select(['id','pid','name'])
            ->get()->toArray();
        $class_ids = [];
        foreach ($param['class_ids'] as $v){
            $class_ids[] = $this->getChildId($class_list,$v);
        }

        $class_arr = $this->flattenArray($class_ids);
        $has = GoodsClass::instance()
            ->where(['df'=>0])
            ->whereIn('id',$class_arr)
            ->exists();
        if(!$has){
            return Normal::returnCode(Normal::FAIL,'分类不存在');
        }
        $res = GoodsClass::instance()
            ->whereIn('id',$class_arr)
            ->update(['show'=>$param['status'],'md'=>time()]);
        if(!$res){
            return Normal::returnCode(Normal::FAIL,'操作失败');
        }

        return Normal::returnCode(Normal::SUC,'操作成功');
    }
}